// socket长链接
angular.module("HTRD_AutoConsole.A").factory('SocketServ', ['$window', function($window) {

  var that = {};
  var webSocketBridge;
  var socketUrl;
  var token = $window.localStorage.getItem('token');

  // 初始化
  var initSocket = function(id) {
     socketUrl = 'ws://106.38.67.196:8001/chat/' + id + '?token=' + token;
     webSocketBridge = new $window.channels.WebSocketBridge();
     webSocketBridge.connect(socketUrl);
     console.log('webSocketBridge', webSocketBridge);
  };

  // 接收消息
  var onMessage = function(callback) {
    webSocketBridge.listen(function(action, stream) {
      callback && callback(action);
    });
  };

  var onClose = function() {
    webSocketBridge.socket.onclose = function() {
      console.log('webSocketBridge.onClose')
    }
  }

  var onError = function() {
    webSocketBridge.socket.onerror = function() {
      console.log('webSocketBridge.onError')
    }
  }

  // 发送消息
  var sendMessage = function(data) {
    webSocketBridge.send({
      token: token,
      data: data
    });
  };

  // 断开连接
  var closeSocket = function() {
    webSocketBridge.socket.close();
  };

  that.initSocket = initSocket;
  that.onMessage = onMessage;
  that.sendMessage = sendMessage;
  that.closeSocket = closeSocket;
  that.onClose = onClose;
  that.onError = onError;
  return that;
}])


// 1. conncat
// 2. 断网
// 3. sent 心跳
// 4. 等待超时 ()
// 5. onclose && onerror
